<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Clients extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/clients/', 'Покупатели');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{

		$data['from'] = $from = $this->input->get('from', true);
		$active = $this->input->get('active', true);
		if ($from == "") $from = 0;
		$this->db->select('users.*, meta.first_name')->from('users')->join('meta', 'users.id = meta.user_id', 'left');


		if ($active !== false) $this->db->where('active', $active);
		if ($this->input->server('REQUEST_METHOD') == "POST") {
			if ($this->input->post('text') != "") {
				$s_text = explode(" ",$this->input->post('text'));
				$like = "(";
				$k = 0;
				foreach ($s_text as $s_seg) {
					$s_seg = trim($s_seg);
					if ($s_seg != "") {
					$k++;
						if ($k != 1) $like .= " or ";
						$like .= "ci_users.email like '%".$s_seg."%' or ";
						$like .= "ci_meta.first_name like '%".$s_seg."%' or ";
						$like .= "ci_users.id like '%".$s_seg."%'";
					}
				}
				$like .= ")";
				$this->db->where($like);
			}
		} else {
			$this->db->limit($this->perpage, $from);
		}

		$data['pages'] = $pages = $this->db->get()->result_array();
		/* pagination */
		if ($this->input->server('REQUEST_METHOD') != "POST") {
			$this->db->select()->from('users');
			if ($active !== false) $this->db->where('active', $active);
			$count = $this->db->count_all_results();
			if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
				$pgng = $from - $this->perpage;
				redirect('admin/clients/index/?from='.$pgng);
			}
			$this->load->library('pagination');
			$config['base_url'] = '/admin/clients/index/';
			$config['total_rows'] = $count;
			$config['page_query_string'] = TRUE;
			$config['per_page'] = $this->perpage;
			$this->pagination->initialize($config);
			$data['paging'] = $this->pagination->create_links();
		}
		/* pagination */

		$data['groups'] = $this->ion_auth->get_groups_as_array();

		$this->layout->view('admin/clients/index', $data);
	}
	public function edit($id = 0) {
		$this->crumps->push('/admin/users/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('users.id', $id)->join('meta', 'users.id = meta.user_id', 'inner')->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/clients');

		$data['orders'] = $this->db->select()->from('orders')->where('order_user', $page['user_id'])->get()->result_array();

		$page['password'] = "";

		$form = new jQuickForm('simple');

		$form->setLabel(($id == 0?"Добавление":"Редактирование").' пользователя');

		$gr = $form->insertGroup()->addClass('col col2');

		$gr->insertInputText('email')->setLabel('E-mail')->setComment('Используется для входа')->addRuleRequired();
		$pass = $gr->insertInputText('password');
		if ($id == 0) {
			$pass->setLabel('Пароль')->setComment('Не менее 8 символов и не более 20');
			$pass->addRuleRequired();
		} else {
			$pass->setLabel('Новый пароль')->setComment('Заполнять только если хотите поменять пароль. Не менее 8 символов и не более 20');
		}

		$groups = $this->ion_auth->get_groups_as_array();
		$select = $form->insertSelect('group_id')->setLabel('Группа');
		foreach ($groups as $group) {
			$select->addOption($group['description'], $group['id']);
		}

		$gr = $form->insertGroup()->addClass('col col2');
		$field = $gr->insertInputText('name_1')->setLabel('Фамилия');
		$field = $gr->insertInputText('name_2')->setLabel('Имя');
		$field = $gr->insertInputText('name_3')->setLabel('Отчество');
		$field = $gr->insertInputText('address_1')->setLabel('Адрес доставки');
		$phone = $gr->insertInputText('phone')->setLabel('Телефон');
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::CLIENT);
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::SERVER);
		$phone->addRuleRequired();

		$field = $gr->insertInputText('urname')->setLabel('Юридическое название');
		$field = $gr->insertInputText('address_2')->setLabel('Юридический адрес');
		$field = $gr->insertInputText('address_3')->setLabel('Фактический адрес');
		$field = $gr->insertInputText('inn')->setLabel('ИНН');
		$field = $gr->insertInputText('kpp')->setLabel('КПП');




		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			$mail_data = $p_data = $this->input->post();
			if ($p_data['password'] == "")
				unset($p_data['password']);
			if (isset($p_data['delete'])) {
				redirect('admin/clients/delete/'.$id.'/');
			}
			$p_data['first_name'] = $p_data['name_1']." ".$p_data['name_2']." ".$p_data['name_3'];
			$result = $this->ion_auth->update_user($id, $p_data);
			if ($result == true) {
				$this->session->set_flashdata('msg', 'Успешно обновлено');
				redirect('admin/clients/edit/' . $id . '/');
			} else {
				$this->session->set_flashdata('error', $this->ion_auth->errors());
			}
		}
		$gr = $form->insertGroupSubmit();
		$gr->insertInputSubmit("Сохранить изменения");
		$gr->insertButton("delete", "Удалить")->setAttribute("style", "color: red;")->setAttribute("onclick", "return confirm('Уверены?');");

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/clients/edit', $data);
	}
	public function delete($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/clients');
		$this->ion_auth->delete_user($id);
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/clients/'.$pgng);
	}
	public function block($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/clients');
		$this->ion_auth->deactivate($id);
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/clients/'.$pgng);
	}
	public function unblock($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/clients');
		$this->ion_auth->activate($id);
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/clients/'.$pgng);
	}
	public function add() {
		return $this->edit(0);
	}
	function push() {
		for ($i = 15; $i < 100; $i++) {
			$p_data = array();
			$p_data['id'] = $i;
			$p_data['group_id'] = 2;
			$this->db->insert('users', $p_data);
			$p_data = array();
			$p_data['id'] = 0;
			$p_data['user_id'] = $i;
			$p_data['company'] = 222;
			$p_data['first_name'] = 222;
			$this->db->insert('meta', $p_data);
		}
	}
}